<?php


namespace Biz\model\advertisement;

use exception\AdminException;
use exception\DbException;

/**
 * @property mixed department_id
 * @property MHhzDepartment|null $department
 */
class MHhzAdmin extends MBaseDbModel
{
    const _CONFIG_FILE_ = 'db_position';

    const _CONFIG_SELECT_ = 'db_position';

    const _DATABASE_ = 'hhz_position';

    const _TABLE_NAME = 'hhz_admin';

    const IS_DELETED_YES = 1;
    const IS_DELETED_NO = 0;

    const IS_SUPER_ADMIN_YES = 1;
    const IS_SUPER_ADMIN_NO = 0;

    public static function getByAccount($account)
    {
        $detail = self::select("*", [
            'account' => $account,
        ]);

        if (!$detail) {
            return null;
        }

        if ($detail[0]['is_deleted'] == self::IS_DELETED_YES) {
            AdminException::invalidStatus();
        }

        return $detail[0];
    }

    public static function addAndReturnDetail($info)
    {
        self::insert([
            'account' => $info['account'],
            'username' => $info['username'],
            'email' => $info['email'],
            'is_super_admin' => self::IS_SUPER_ADMIN_NO,
            'is_deleted' => self::IS_DELETED_NO,
            'department_id' => 0,
            'wx_userid' => $info['wx_userid'],
        ]);

        $id = self::id();
        if (!$id) {
            DbException::writeFailed();
        }

        return array_merge($info, ['id' => $id]);
    }

    public static function getById($id)
    {
        return self::get('*', ['id' => $id, 'is_deleted' => self::IS_DELETED_NO]);
    }

    public static function getAll($account = '')
    {
        $where = ['is_deleted' => self::IS_DELETED_NO];

        if ($account) {
            $where['account'] = $account;
        }

        return self::select(["[>]".MHhzDepartment::_TABLE_NAME => ["department_id" => "id"]],
            [
                self::_TABLE_NAME.'.id',
                self::_TABLE_NAME.'.account',
                self::_TABLE_NAME.'.username',
                self::_TABLE_NAME.'.department_id',
                self::_TABLE_NAME.'.wx_userid',
                self::_TABLE_NAME.'.email',
                self::_TABLE_NAME.'.is_super_admin',
                self::_TABLE_NAME.'.created_at',
                self::_TABLE_NAME.'.updated_at',
                MHhzDepartment::_TABLE_NAME.'.name(department_name)',
            ],
            $where);
    }

    public static function getWxUserIdByUserId($userId)
    {
        $where = [
            'user_id' => $userId
        ];

        $r = self::select(['user_id', 'wx_userid'], $where);

        $res = [];

        if ($r) {
            foreach ($r as $item) {
                $res[$item['user_id']] = $item['wx_userid'];
            }
        }

        return $res;
    }
}
